#include "dialogrun.h"
#include "ui_dialogrun.h"

#include <QDebug>

Dialogrun::Dialogrun(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialogrun)
{
    ui->setupUi(this);
}

Dialogrun::~Dialogrun()
{
    delete ui;
}

void Dialogrun::on_pushButton_2_clicked()
{
    this->close();
}

//打开串口
void Dialogrun::on_pushButton_clicked()
{
#if 0
    //QString portName = ui->portNameComboBox->currentText();   //获取串口名
#ifdef Q_OS_LINUX
    //myCom = new QextSerialPort("/dev/" + portName);
    myCom = new QextSerialPort("/dev/ttyUSB0");
#elif defined (Q_OS_WIN)
    myCom = new QextSerialPort(portName);
#endif
    connect(myCom, SIGNAL(readyRead()), this, SLOT(readMyCom()));

    //设置波特率
//    myCom->setBaudRate((BaudRateType)ui->baudRateComboBox->currentText().toInt());
    myCom->setBaudRate((BaudRateType)115200);

    //设置数据位
//    myCom->setDataBits((DataBitsType)ui->dataBitsComboBox->currentText().toInt());
    myCom->setDataBits((DataBitsType)8);

#if 0
    //设置校验
    switch(ui->parityComboBox->currentIndex()){
    case 0:
         myCom->setParity(PAR_NONE);
         break;
    case 1:
        myCom->setParity(PAR_ODD);
        break;
    case 2:
        myCom->setParity(PAR_EVEN);
        break;
    default:
        myCom->setParity(PAR_NONE);
        qDebug("set to default : PAR_NONE");
        break;
    }
#elif 1
    myCom->setParity(PAR_NONE);//设置校验
#endif

#if 0
    //设置停止位
    switch(ui->stopBitsComboBox->currentIndex()){
    case 0:
        myCom->setStopBits(STOP_1);
        break;
    case 1:
 #ifdef Q_OS_WIN
        myCom->setStopBits(STOP_1_5);
 #endif
        break;
    case 2:
        myCom->setStopBits(STOP_2);
        break;
    default:
        myCom->setStopBits(STOP_1);
        qDebug("set to default : STOP_1");
        break;
    }
#elif 1
    myCom->setStopBits(STOP_1);
#endif

    //设置数据流控制
    myCom->setFlowControl(FLOW_OFF);
    //设置延时
    myCom->setTimeout(TIME_OUT);

    if(myCom->open(QIODevice::ReadWrite))
    {
        //QMessageBox::information(this, tr("打开成功"), tr("已成功打开串口") + portName, QMessageBox::Ok);
        QMessageBox::information(this, tr("打开成功"), tr("已成功打开串口ttyUSB0"), QMessageBox::Ok);
        //界面控制
         ui->pushButton->setEnabled(false);
         ui->pushButton_3->setEnabled(true);
    }
    else{
        QMessageBox::critical(this, tr("打开失败"), tr("未能打开串口 ") + tr("ttyUSB0") + tr("\n该串口设备不存在或已被占用"), QMessageBox::Ok);
        return;
    }
//    ui->statusBar->showMessage(tr("打开串口成功"));
#endif
    if(ui->pushButton->text()==tr("打开串口"))
    {
        my_serialport = new QSerialPort;
        my_serialport->setPortName("ttyUSB0");//串口名称
        my_serialport->open(QIODevice::ReadWrite);//打开串口
        my_serialport->setBaudRate(115200);//串口波特率设置 (115200)
        my_serialport->setDataBits(QSerialPort::Data8);//设置数据位数（8位）
        my_serialport->setParity(QSerialPort::NoParity);//设置奇偶校验 (无校验位）
        my_serialport->setStopBits(QSerialPort::OneStop);//设置停止位（1位）
        my_serialport->setFlowControl(QSerialPort::NoFlowControl);//设置流控制
        //界面控制（理论要判断是否打开成功在做界面控制切换）
        ui->pushButton->setText(tr("关闭串口"));
#if 0
        //连接信号槽
        QObject::connect(my_serialport, &QSerialPort::readyRead, this, &Dialogrun::Read_Data);
#else
       timer = new QTimer(this);
       connect(timer,SIGNAL(timeout()),this,SLOT(Read_Data()));
       timer->start(10);
#endif
    }
    else
    {
#if 0
        timer->stop();
#endif
        //关闭串口
        //my_serialport->clear();
        my_serialport->close();
        my_serialport->deleteLater();

        ui->pushButton->setText(tr("打开串口"));
    }
}

//读取数据
void Dialogrun::Read_Data()
{
    QByteArray buf;
    if(bClosing==false)
    {
        bClosing=true;
        byteLen=my_serialport->bytesAvailable();//返回串口缓冲区字节数
        buf = my_serialport->readAll();//返回读取的字节
    }
    if(!buf.isEmpty())
    {
#if 0
        QString str = ui->textEdit->toPlainText();//这个应该是字符
        str+=buf.toHex().data();//以十六进制显示
        str =str.toUpper();//转换为大写
        ui->textEdit->clear();
        ui->textEdit->append(str);
        if(buf[0]==0x55)
            ui->lineEdit->setText("123");
        else
            ui->lineEdit->setText("100/2");
#else
        QDateTime time =QDateTime::currentDateTime();//获得系统现在的时间
      //QString str1=time.toString("yyyy-MM-dd hh:mm:ss ddd");//设置显示格式
        QString str1=time.toString("hh:mm:ss");//设置显示格式
        int i=0;//找到0X55头
        for (;i<byteLen;i++)
        {
            if(0x55==buf[i])
            {
                break;
            }
        }
        if(i+11>byteLen){return;}
        else
        {
            switch(buf[i+1])
            {
                case 0x50:
                    break;
                case 0x51:
                    //0x55 0x51 加速度
                    a[0]=((buf[i+3]<<8)|buf[i+2])/32768*16;//g,9.8m/s^2
                    a[1]=((buf[i+5]<<8)|buf[i+4])/32768*16;//g,9.8m/s^2
                    a[2]=((buf[i+7]<<8)|buf[i+6])/32768*16;//g,9.8m/s^2
                    a[3]=((buf[i+9]<<8)|buf[i+8]);//  ℃
                    Temperature=a[3]/100.0; //0x55 0x51 0x52 0x53 0x54 温度℃
                    break;
                case 0x52:
                    //0x55 0x52 角速度
                    w[0]=((buf[i+3]<<8)|buf[i+2])/32768.0*2000;
                    w[1]=((buf[i+5]<<8)|buf[i+4])/32768.0*2000;
                    w[2]=((buf[i+7]<<8)|buf[i+6])/32768.0*2000;
                    w[3]=((buf[i+9]<<8)|buf[i+8]);
                    //Temperature=w[3]/100.0; //0x55 0x51 0x52 0x53 0x54 温度℃
                    break;
                case 0x53:
                    //0x55 0x53 角度
                    Angle[0]=((buf[i+3]<<8)|buf[i+2])/32768.0*180;
                    Angle[1]=((buf[i+5]<<8)|buf[i+4])/32768.0*180;
                    Angle[2]=((buf[i+7]<<8)|buf[i+6])/32768.0*180;
                    Angle[3]=((buf[i+9]<<8)|buf[i+8]);
                    //Temperature=Angle[3]/100.0; //0x55 0x51 0x52 0x53 0x54 温度℃
                    break;
                case 0x54:
                    //0x55 0x54 磁场
                    h[0]=((buf[i+3]<<8)|buf[i+2]);
                    h[1]=((buf[i+5]<<8)|buf[i+4]);
                    h[2]=((buf[i+7]<<8)|buf[i+6]);
                    h[3]=((buf[i+9]<<8)|buf[i+8]);
                    //Temperature=h[3]/100.0; //0x55 0x51 0x52 0x53 0x54 温度℃
                    break;
                case 0x55:
                    //0x55 0x55  端口
                    Port[0]=((buf[i+3]<<8)|buf[i+2]);
                    Port[1]=((buf[i+5]<<8)|buf[i+4]);
                    Port[2]=((buf[i+7]<<8)|buf[i+6]);
                    Port[3]=((buf[i+9]<<8)|buf[i+8]);
                    break;
                case 0x56:
                    //0x55 0x56  气压  高度
                    Pressure=((buf[i+5]<<24)|(buf[i+4]<<16)|(buf[i+3]<<8)|buf[i+2]);
                    Altitude=((buf[i+9]<<24)|(buf[i+8]<<16)|(buf[i+7]<<8)|buf[i+6]);
                    break;
                case 0x57:
                    break;
                default:
                    break;
            }
        }
        ui->lineEdit->setText(str1);
        ui->lineEdit_2->setText(QString::number(byteLen));
        ui->lineEdit_3->setText(QString::number(a[0]));//x轴加速度
        ui->lineEdit_4->setText(QString::number(a[1]));//y轴加速度
        ui->lineEdit_5->setText(QString::number(a[2]));//z轴加速度
        ui->lineEdit_6->setText(QString::number(w[0]));//x轴角速度
        ui->lineEdit_7->setText(QString::number(w[1]));//y轴角速度
        ui->lineEdit_8->setText(QString::number(w[2]));//z轴角速度
        ui->lineEdit_9->setText(QString::number(Angle[0]));//x轴角度
        ui->lineEdit_10->setText(QString::number(Angle[1]));//y轴角度
        ui->lineEdit_11->setText(QString::number(Angle[2]));//z轴角度
        ui->lineEdit_12->setText(QString::number(h[0]));//x轴磁场
        ui->lineEdit_13->setText(QString::number(h[1]));//y轴磁场
        ui->lineEdit_14->setText(QString::number(h[2]));//z轴磁场
        ui->lineEdit_15->setText(QString::number(Temperature));//温度
        ui->lineEdit_16->setText(QString::number(Pressure));//textChanged 气压
        ui->lineEdit_17->setText(QString::number(Altitude));//高度
        bClosing=false;
#endif
    }
    buf.clear();
    byteLen=0;
    QThread::msleep(10);
#if 0
    my_serialport->close();
    my_serialport->deleteLater();
    ui->pushButton->setText(tr("打开串口"));
#endif
}
